package com.ljh.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljh.common.lang.Result;
import com.ljh.entity.Blog;
import com.ljh.entity.Tag;
import com.ljh.entity.Type;
import com.ljh.service.TagService;
import com.ljh.service.TypeService;
import com.ljh.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
public class TypeController {
    @Autowired
    TypeService typeService;



    @GetMapping("/type")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 500);
        IPage pageData = typeService.page(page, new QueryWrapper<Type>().orderByDesc("id"));

        return Result.succ(pageData);
    }


    @RequiresAuthentication
    @PostMapping("/type/add")
    public Result add(@Validated @RequestBody Type type) {
        Type temp = null;
        if(type.getId() != null) {
            temp = typeService.getById(type.getId());
            temp.setCount(type.getCount()+1);
        } else {
            temp = new Type();
            temp.setCount(type.getCount());
            temp.setType(type.getType());
        }
        typeService.saveOrUpdate(temp);
        return Result.succ(null);
    }

    @RequiresAuthentication
    @PostMapping("/type/sub")
    public Result sub(@Validated @RequestBody Type type) {
        Type temp = null;
        if(type.getId() != null) {
            temp = typeService.getById(type.getId());
            temp.setCount(type.getCount() == 0? 0 : (type.getCount()-1));
        } else {
            temp = new Type();
            temp.setCount(type.getCount());
            temp.setType(type.getType());
        }
        typeService.saveOrUpdate(temp);
        return Result.succ(null);
    }

    @PostMapping("/type/delete/{id}")
    @ResponseBody
    public Result del(@PathVariable(name = "id") Long id){
        boolean result = typeService.removeById(id);
        if(result == true){
            return Result.succ(null);

        }else {
            return Result.fail(null);
        }
    }

    @PostMapping("/type/search")
    public Result Search(@Validated @RequestBody Type type) {

        Page page = new Page(1, 500);
        IPage pageData = typeService.page(page, new QueryWrapper<Type>().like("type", type.getType()));

        return Result.succ(pageData);
    }
}
